<template>
  <div id="home">
    <div class="place"></div>
    <el-menu
      class="menu"
      mode="horizontal"
      @select="onMenuClick"
      background-color="#012456"
      text-color="#fff"
      active-text-color="#fff"
    >
      
      <el-menu-item ><div class="logo"><img :src="logoUrl" class="logo-img"/><h3 class="logo-text" style="display:inline">数字货币量化交易机器人</h3></div></el-menu-item>
      <el-menu-item index="1">新建任务</el-menu-item>
      <el-menu-item index="2">交易报表</el-menu-item>
      <el-menu-item index="3">行情分析</el-menu-item>
      <el-submenu index="4">
        <template slot="title">设置</template>
        <el-menu-item index="4-1">API设置</el-menu-item>
        <el-menu-item index="4-2">授权</el-menu-item>
        <el-menu-item index="4-3">退出</el-menu-item>
      </el-submenu>
      <el-submenu index="5">
        <template slot="title">帮助</template>
        <el-menu-item index="5-1">检查更新…</el-menu-item>
        <el-menu-item index="5-2">关于</el-menu-item>
      </el-submenu>
    </el-menu>

    
      <el-button-group class="min-max-close-button">
        <el-button type="text" size="mini" style="margin-right:10px;" @click="closeWin"><img :src="closeUrl" style="width:16px;"/></el-button>
        <el-button type="text" size="mini" style="margin-right:10px;" @click="maxWin"><img :src="isWindowMaxed ? unmaxUrl : maxUrl" style="width:16px;"/></el-button>
        <el-button type="text" size="mini" style="margin-right:10px;" @click="minWin"><img :src="minUrl" style="width:16px;"/></el-button>
      </el-button-group>
    

    <el-row class="common-button">
      <el-button-group class="button-group">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="refresh"></el-button>
        <el-button type="primary" icon="el-icon-menu" size="mini" @click="displayMode = 1"></el-button>
        <el-button type="primary" icon="el-icon-document" size="mini" @click="displayMode = 2"></el-button>
      </el-button-group>
    </el-row>


    <el-button class="new-button" v-if="taskList.length == 0" type="primary" @click="createTask" size="medium">新建任务</el-button>

   <el-row v-if="displayMode == 2 && taskList.length > 0" style="">
        <el-table  :data="taskList"  :border="true" size="small" :highlight-current-row="true" style="width: 100%;height:100%;">
        <el-table-column   prop="state"   label="状态"   min-width="80" header-align="center" align="center">
          <template slot-scope="scope">
          <el-switch
                  style="margin-left:2px;"
                  v-model="scope.row.state"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#C1C1C1"
                  :width="30"
                  @change="switchChange(scope.$index)"
                ></el-switch>
          </template>
          </el-table-column>
       <el-table-column  prop="_id" label="操作" min-width="90" header-align="center" align="center" :show-overflow-tooltip="true">
         <template slot-scope="scope">
             <el-button @click="onUpdateTask(scope.row._id)" type="text" size="small">修改</el-button>
             <el-button @click="onRemoveTask(scope.row._id)" type="text" size="small" style="color:red">删除</el-button>
         </template>
        </el-table-column>
       <el-table-column  prop="_id" label="ID" min-width="110" header-align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column  prop="symbol" label="交易对" min-width="110" header-align="center" align="center">
           <template slot-scope="scope">
                    <span>{{ scope.row.symbol.toUpperCase() }}</span>
          </template>
        </el-table-column>
        <el-table-column  prop="loopCount" label="累计止盈" min-width="80" header-align="center" align="center" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span>{{ scope.row.loopCount + ' 单'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalMoney" label="持仓金额" min-width="100" header-align="center" align="right" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="totalAmount" label="持仓数量" min-width="100" header-align="center" align="right" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="buyTradeCount" label="本轮已补单" width="100" header-align="center" align="center" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span>{{ scope.row.buyTradeCount + ' 单'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="buyMoneys" label="补单金额"  min-width="130" header-align="center" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span v-for="(item,index) in scope.row.buyMoneys" :key="index">
                [{{'第'+(index + 1)+'单:'+item.value}}]
              </span>
          </template>
        </el-table-column>
        <el-table-column prop="depth" label="深度"  width="70" header-align="center" align="center" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span>{{ scope.row.depth ?  scope.row.depth + '%' : '30%'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reboundPercent"  label="反弹百分比" width="90" header-align="center" align="right" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span>{{ scope.row.reboundPercent + '%'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="profitPercent" label="止盈百分比" width="90" header-align="center" align="right" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span>{{ scope.row.profitPercent + '%'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fallBackPercent" label="回降百分比" width="90" header-align="center" align="right" :show-overflow-tooltip="true">
           <template slot-scope="scope">
              <span>{{ scope.row.fallBackPercent + '%'}}</span>
          </template>
        </el-table-column>
      </el-table>
 </el-row>

    <el-row class="card-body" v-if="displayMode == 1">
      <draggable v-model="taskList" @update="datadragEnd" :options="{animation:200}">
        <transition-group name="cell" tag="ul">
          <el-card class="box-card" v-for="(item,index) in taskList" :key="item._id">
            <div slot="header" class="header">
              <div class="header-item left">
                <el-switch
                  style="margin-left:2px;"
                  v-model="item.state"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#C1C1C1"
                  :width="30"
                  @change="switchChange(index)"
                ></el-switch>
              </div>
              <div class="header-item center">
                <div class="lamp" :class="item.state == 1 ? 'runing' : ''"></div>
              </div>
              <div class="header-item right">
                <el-button-group>
                  <el-button icon="el-icon-s-platform" size="mini" @click="onOpenDisplayer(item._id,item.symbol)"></el-button>
                  <el-button icon="el-icon-edit" size="mini" @click="onUpdateTask(item._id)"></el-button>
                  <el-button icon="el-icon-delete" size="mini" @click="onRemoveTask(item._id)"></el-button>
                </el-button-group>
              </div>
            </div>
            <div class="card-content" style="text-align:center;height:100px;display:flex;flex-direction:column;justify-content:center">
              <div><el-link type="primary"><h3> {{item.symbol.toUpperCase()}}</h3></el-link></div>
              <div>
                <el-divider style="margin: 12px 0;!important" content-position="center">累计止盈</el-divider>
                 <el-link type="success"> 
                <strong style="font-size:22px;">{{item.loopCount - 1}}</strong>单</el-link>
              </div>
              <!-- <div><el-link type="success">交易策略：
                <strong v-if="item.buyMethod == '1'">斐波那契</strong>
                <strong v-if="item.buyMethod == '2'">倍投</strong>
                <strong v-if="item.buyMethod == '3'">立方倍投</strong>
               </el-link></div> -->
             </div>
             <div :id="'id_'+item._id" class="laser " >
             </div>
          </el-card>
        </transition-group>
      </draggable>
    </el-row>


    <el-dialog title="授权" :visible.sync="authFormVisible" :close-on-click-modal="false">
      <el-form ref="authForm" :model="authForm" :rules="authEditRules">
        <el-form-item label="邮箱" prop="email" label-width="120px">
          <el-input v-model="authForm.email" spellcheck="false" autocomplete="off" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="授权码" prop="authCode" label-width="120px">
          <el-input type="textarea" rows="3" spellcheck="false" v-model="authForm.authCode" autocomplete="off" maxlength="512"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align:right;color:#f56058">
        <p>{{authInfo.content}}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="authFormVisible = false">关 闭</el-button>
        <el-button type="primary" @click="onAuthSave('authForm')">授 权</el-button>
      </div>
    </el-dialog>


    <el-dialog title="API设置" :visible.sync="keyFormVisible" :close-on-click-modal="false">
      <el-form ref="keyForm" :model="keyForm" :rules="keyEditRules">
        <el-form-item label="Access Key" prop="accessKey" label-width="100px">
          <el-input v-model="keyForm.accessKey" autocomplete="off" maxlength="50" show-password></el-input>
        </el-form-item>
        <el-form-item label="Secret Key" prop="secretKey" label-width="100px">
          <el-input v-model="keyForm.secretKey" autocomplete="off" maxlength="50" show-password></el-input>
        </el-form-item>
         <el-form-item label="主机选择" label-width="100px">
            <el-radio v-model="keyForm.host" label="api.huobi.de.com">境内【api.huobi.de.com】（不稳定）</el-radio>
            <el-radio v-model="keyForm.host" label="api.huobi.pro">境外【api.huobi.pro】（推荐）</el-radio>
            <el-radio v-model="keyForm.host" label="api-aws.huobi.pro">AWS主机【api-aws.huobi.pro】（AWS用户推荐）</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="onTestKey('keyForm')">测试连接</el-button>
        <el-button @click="keyFormVisible = false">关 闭</el-button>
        <el-button type="primary" @click="onKeySave('keyForm')">保 存</el-button>
      </div>
    </el-dialog>

      <el-dialog title="快速设置"  :visible.sync="showMoneyDialog"   width="500px" :close-on-click-modal="false" >
         <el-form ref="moneySettingForm" :model="moneySettingForm"  :rules="moneySettingRules" label-width="110px">
            <el-form-item label="下单策略" :required="true">
              <el-radio-group v-model="moneySettingForm.method">
                <el-radio label="1">斐波那契</el-radio>
                <el-radio label="2">倍投</el-radio>
                <el-radio label="3">立方倍投</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="买入单数" :required="true">
              <el-input-number v-model="moneySettingForm.count" :min="1" :max="10" :step="1"></el-input-number>
            </el-form-item>

            <el-form-item label="首单金额" prop="money">
              <el-input
                v-model="moneySettingForm.money"
                v-number-input.float="{ min: 1 , max:1000,decimal:2}"
                placeholder="请输入首次下单金额"
              ></el-input>
            </el-form-item>
         </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showMoneyDialog = false">取 消</el-button>
          <el-button type="primary" @click="onSettingEnter('moneySettingForm')">确 定</el-button>
        </span>
      </el-dialog>


    <el-dialog :title="taskEdit._id ? '编辑任务':'创建任务'" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="750px">
      <el-form ref="taskEdit" :model="taskEdit" :rules="taskEditRules" label-width="110px">
        <el-tabs v-model="currentTab" tab-position="top" style="height:320px;">
          <el-tab-pane label="交易对设置">
            <p v-if="!taskEditable" style="float:right;color:#f56058;">已发生交易，部分选项不允许修改。</p>
            <el-form-item label="选择交易对" prop="symbol" >
              <el-select v-model="taskEdit.symbol" :disabled="!taskEditable" filterable placeholder="选择交易对" :clearable="true" @change="onSymbolChange">
                <el-option
                  v-for="(item,key) in symbolList"
                  :key="key"
                  :label="item.symbol.toUpperCase()"
                  :value="item.symbol"
                >
                <span style="float: left">{{ item.symbol.toUpperCase() }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">计价币种：{{ item['quote-currency'] }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="主流币种" >
              <el-radio-group v-model="taskEdit.symbol" :disabled="!taskEditable" @change="onRadioSymbolChange">
                <el-radio label="btcusdt" border>BTCUSDT</el-radio>
                <el-radio label="ethusdt" border>ETHUSDT</el-radio>
                <el-radio label="xrpusdt" border>XRPUSDT</el-radio>
              </el-radio-group>
            </el-form-item>


            <el-form-item  v-if="taskEdit.symbol != '' && taskEdit.symbol.length > 0" label-width="30px">
              <el-checkbox v-model="taskEdit.accountBalance" :disabled="!taskEditable" @change="onAccountBalanceChange">使用账户余额初始化</el-checkbox>
            </el-form-item>

            <el-form-item label="已交易数量" v-if="taskEdit.accountBalance && taskEdit.symbol != '' && taskEdit.symbol.length > 0">
              <el-input  v-model="taskEdit.totalAmount" :disabled="!taskEditable" style="width:80%;margin-right:5px;"  :key="taskAmountPrecision" v-number-input.float="{ min: 0, decimal:taskAmountPrecision }" >
                 <template slot="append">{{taskBaseCurrency.toUpperCase()}}</template>
              </el-input>
              <el-button v-if="taskEditable" @click="getAccountBalance" size="mini" type="success">加载账户余额</el-button>
            </el-form-item>

            <el-form-item label="已交易金额" v-if="taskEdit.accountBalance && taskEdit.symbol != '' && taskEdit.symbol.length > 0">
              <el-input  v-model="taskEdit.totalMoney" :disabled="!taskEditable" style="width:80%" :key="taskValuePrecision" v-number-input.float="{ min: 0, decimal:taskValuePrecision}" >
                <template slot="append">{{taskQuoteCurrency.toUpperCase()}}</template>
              </el-input>
            </el-form-item>

              
            



          </el-tab-pane>

          <el-tab-pane label="补单策略">
            
            <div style="display:flex;flex-wrap:wrap;padding: 5px 90px;">
              <el-form-item  style="width:250px;" v-for="(item, index) in taskEdit.buyMoneys" :key="index" 
               :prop="'buyMoneys.' + index + '.value'"
              :rules="{
                required: true, message: '金额不能为空'
              }"
             
               :label=" index == 0 ? '首单金额' : '第' + (index + 1) +'单金额'" >
              <el-input
                size="small"
                v-model="item.value"
                v-number-input.float="{ min: 1 , max:1000,decimal:2}"
                :placeholder="'第' + (index + 1) +'单金额'"
              ></el-input>
            </el-form-item>
            <el-form-item label-width="30px">
              <el-button @click="addMoneyInput" size="mini"><i class="el-icon-plus"></i></el-button>
              <el-button @click="settingMoney" size="mini" type="success">快速设置</el-button>
              <el-button @click="removeMoneyInput" size="mini"><i class="el-icon-minus"></i></el-button>
            </el-form-item>

            </div>
            

            <!-- <el-form-item label="深度" style="padding-right:20px;">
              <el-slider
                v-model="taskEdit.buyLevel"
                style="width:80%"
                :min="1"
                :max="9"
                :step="1"
                :marks="buyLevelMarks"
                :show-tooltip="false"
                show-stops
              ></el-slider>
            </el-form-item> -->

              <el-form-item label="深度" style="padding-right:20px;">
              <el-slider
                v-model="taskEdit.depth"
                style="width:80%"
                :min="10"
                :max="90"
                :step="1"
                :marks="depthMarks"
                :show-tooltip="true"
                :format-tooltip="formatDepthTooltip"
                show-stops
              ></el-slider>
            </el-form-item>

            <el-form-item prop="reboundPercent">
              <template slot="label">
                <el-tooltip effect="dark" placement="right">
                  <template slot="content">
                    提示：价格达到根据深度计算的买入价格后不下单，而是反弹一定百分比后买入。
                    <br />如果为0，则立即买入。
                  </template>
                  <i class="el-icon-warning" style="color:yellow"></i>
                </el-tooltip>反弹百分比
              </template>
              <el-input
                placeholder="请输入百分比"
                v-number-input.float="{ min: 0 , max:10,decimal:2}"
                v-model="taskEdit.reboundPercent"
              >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>

            
          </el-tab-pane>

          <el-tab-pane label="止盈策略">
            <el-form-item label="止盈百分比" prop="profitPercent">
              <el-input
                placeholder="请输入百分比"
                v-model="taskEdit.profitPercent"
                v-number-input.float="{ min: 1 , max:10,decimal:2}"
              >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>

            <el-form-item prop="fallBackPercent">
              <template slot="label">
                <el-tooltip effect="dark" placement="right">
                  <template slot="content">
                    提示：价格从最高点回落一定百分比后卖出。
                    <br />如果为0，则达到止盈百分比立即卖出。
                  </template>
                  <i class="el-icon-warning" style="color:yellow"></i>
                </el-tooltip>回降百分比
              </template>
              <el-input
                placeholder="请输入百分比"
                v-model="taskEdit.fallBackPercent"
                v-number-input.float="{ min: 0 , max:10,decimal:2}"
              >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="onSave('taskEdit')">保存</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>

  
</template>

<script>
import draggable from "vuedraggable";
import { Loading } from 'element-ui';
const { ipcRenderer,remote } =  window.require('electron');
const math = require('mathjs')
export default {
  name: "Home",
  components: {
    draggable,
  },
  data() {
    var validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入邮箱'));
        } else {
          var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          if(reg.test(value)){
            callback();
          }else{
             callback(new Error('请输入正确的邮箱'));
          }
          
        }
      };
    return {
       logoUrl:require("@/assets/img/logo.png"),
       closeUrl:require("@/assets/img/close.png"),
       minUrl:require("@/assets/img/min.png"),
       unmaxUrl:require("@/assets/img/max.png"),
       maxUrl:require("@/assets/img/full-max.png"),
       isWindowMaxed : false,
      loading:false,
      displayMode:1,
      taskList: [
       
      ],
      currentTab: "0",
      dialogFormVisible: false,
      showMoneyDialog:false,
      symbolList: [
        
      ],
      moneySettingForm:{
         method:'1',
         count:1,
         money:''
      },
      defaultTask: {
        state:0,
        symbol: "",
        buyTradeCount:0,
        buyMoneys:[{value:''}],
        buyLevel: 3,
        depth:30,
        reboundPercent: 0,
        buyBasePrice:'0',
        profitPercent: 2.5,
        fallBackPercent: 0,
        loopCount:1,
        accountBalance:false,
        totalAmount:'0',
        totalMoney:'0',
        sort:0,
        quit:0,
        stopTrade:0
      },
      taskEdit: {
        state:0,
        symbol: "",
        buyTradeCount:0,
        buyMoneys:[{value:''}],
        buyLevel: 3,
        depth:30,
        reboundPercent: 0,
        buyBasePrice:'0',
        profitPercent: 2.5,
        fallBackPercent: 0,
        loopCount:1,
        accountBalance:false,
        totalAmount:'0',
        totalMoney:'0',
        sort:0,
        quit:0,
        stopTrade:0
      },
      taskBaseCurrency:'',
      taskQuoteCurrency:'',
      taskAmountPrecision:8,
      taskValuePrecision:8,
      taskEditable:true,
      buyLevelMarks:{1:'10%',2:'20%',3:'30%',4:'40%',5:'50%',6:'60%',7:'70%',8:'80%',9:'90%'},
      depthMarks:{10:'10%',20:'20%',30:'30%',40:'40%',50:'50%',60:'60%',70:'70%',80:'80%',90:'90%'},
      taskEditRules: {
        symbol: [{ required: true, message: "请选择币种", trigger: "change" }],
        money: [{ required: true, message: "金额不能为空" }],
        reboundPercent: [{ required: true, message: "百分比不能为空" }],
        profitPercent: [{ required: true, message: "百分比不能为空" }],
        fallBackPercent: [{ required: true, message: "百分比不能为空" }],
      },
       moneySettingRules: {
        money: [{ required: true, message: "金额不能为空" }],
      },
      keyFormVisible:false,
      keyForm: {
          accessKey: '',
          secretKey: '',
          host:'api.huobi.de.com'
        },
      keyEditRules: {
        accessKey: [{ required: true, message: "Access Key不能为空"}],
        secretKey: [{ required: true, message: "Secret Key不能为空" }],
      },
      timerId:null,
      authFormVisible : false,
      authForm : {
        email:'',
        authCode:'',
      },
      authInfo:{
        valid:false,
        content:'',
      },
      authEditRules: {
        email: [{ validator: validateEmail, trigger: 'blur'}],
        authCode: [{ required: true, message: "授权码不能为空" }],
      },
    };
  },
  methods: {
    onMenuClick(index, indexPath) {
      switch (index) {
        case "1":
         this.createTask();
          break;
        case "2":
          ipcRenderer.send('openTrade');
          // this.initSymbol();
          break;
        case "3":
          ipcRenderer.send('openMarket');
          break;
        case "4-1":
          this.loadKey();
          this.keyFormVisible = true;
          break;
        case "4-2":
         this.loadAuth();
          this.authFormVisible = true;
          break;
        case "4-3":
          ipcRenderer.send('quit');
          break;
        case "5-1":
         ipcRenderer.send('checkUpdate');
          break;
        case "5-2":
          ipcRenderer.send('openAbout');
          break;
        default:
      }
    },
    formatDepthTooltip(value){
      return value + '%';
    },
    switchChange(index) {
      // alert(1)
      let data = this.taskList[index];
      if(data.state == 0){
        this.$confirm('确定要停止任务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.updateTaskState(data);
        }).catch(() => {
                this.taskList[index].state = 1;  
        });
      }else{
       
        ipcRenderer.once('checkAuth-res',(event,result)=>{
         if(!result.success){
            this.$message.error('授权码验证异常。');
            this.taskList[index].state = 0;  
            return;
          }
           if(!result.data.valid){
            this.$message.error(result.data.content);
            this.taskList[index].state = 0;  
            return;
          }
           this.updateTaskState(data);
        })
        ipcRenderer.send('checkAuth')

      }
      
    },
    updateTaskState(data){
      ipcRenderer.once('updateTaskState-res',(event,res)=>{
        console.log('updateTaskState-res',res)
         if(res.success){
            if(res.data > 0){
              if(data.state == 1){
                ipcRenderer.send('startupTask',data._id)
                this.$message.success('任务已启动');
              }else{
                ipcRenderer.send('shutdownTask',data._id)
              }
            }
          }
      })

      ipcRenderer.send('updateTaskState',{_id:data._id,state:data.state})

    },
    createTask(){
          this.taskEditable = true;
          this.currentTab = '0';
          this.taskEdit = JSON.parse(JSON.stringify(this.defaultTask))
          this.dialogFormVisible = true;
          this.loadSymbol(()=>{})
    },
    onUpdateTask(_id){
      ipcRenderer.once('getTaskById-res',(event,res)=>{
        console.log('getTaskById-res',res)
        if(res.success){
              if(res.data.state == 1){
                this.$message.error('任务运行中，不允许修改。');
                return;
              }

                this.currentTab = '0';
                if(res.data.accountBalance == undefined){
                  res.data.accountBalance = false;
                }
                 if(res.data.depth == undefined){
                  res.data.depth = 30;
                }
                 if(res.data.quit == undefined){
                  res.data.quit = 0;
                }
                 if(res.data.stopTrade == undefined){
                  res.data.stopTrade = 0;
                }
              this.taskEdit = res.data;
                this.dialogFormVisible = true;
                this.loadSymbol(()=>{
                  console.log('loadSymbol callback')
                  if(this.taskEdit.accountBalance){
                      this.updateTaskCurrency(this.taskEdit.symbol);
                  }
                })
               
               ipcRenderer.once('existsTradeForTaskId-res',(event,exists)=>{
                 console.log('existsTradeForTaskId-res',exists)
                  this.taskEditable = !exists;
               })
                ipcRenderer.send('existsTradeForTaskId',_id);
                
            }
      })
      ipcRenderer.send('getTaskById',_id);
    
    },
    onRemoveTask(_id){
      ipcRenderer.once('getTaskById-res',(event,res)=>{
        console.log('getTaskById-res',res)
         if(res.success){
            if(res.data.state == 1){
              this.$message.error('任务运行中，不允许删除。');
              return;
            }

            this.removeTask(_id);
          }
      })
      ipcRenderer.send('getTaskById',_id);

    },
    removeTask(_id){
      this.$confirm('删除后不能恢复，确定要删除任务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

            ipcRenderer.once('removeTaskById-res',(event,res)=>{
              console.log('removeTaskById-res',res)
                if(res.success){
                    if(res.data > 0){
                      let list = this.taskList;
                      let index = -1;
                    for(var i in list){
                      if(list[i]._id == _id){
                        index = i;
                        break;
                      }
                    }
                    if(index > -1){
                      this.taskList.splice(index, 1); 
                      this.$message.success('任务已删除。');
                    }
                    
                    }
                  }
            })

          ipcRenderer.send('removeTaskById',_id);

        }).catch(() => {
               
        });
    },
    onSave(formName) {

       ipcRenderer.once('checkAuth-res',(event,result)=>{
        if(!result.success){
          return;
        }
        if(!result.data.valid){
          this.$message.error(result.data.content);
          return;
        }
        this.saveTask(formName);
        })

       ipcRenderer.send('checkAuth')

    },
    saveTask(formName){
        this.$refs[formName].validate((valid, obj) => {
        if (valid) {
          if(this.taskEditable){
            if(this.taskEdit.totalAmount == ''){
              this.taskEdit.totalAmount = '0'
            }
            if(this.taskEdit.totalMoney == ''){
              this.taskEdit.totalMoney = '0'
            }

            if(parseFloat(this.taskEdit.totalAmount) != 0 && parseFloat(this.taskEdit.totalMoney) == 0){
               this.$message.error('初始交易金额不能为空。');
              return;
            }
             if(parseFloat(this.taskEdit.totalMoney) != 0 && parseFloat(this.taskEdit.totalAmount) == 0){
              this.$message.error('初始交易数量不能为空。');
              return;
            }
          }
          let loadingInstance  = this.$loading({ lock: true,text: 'Loading',spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
          ipcRenderer.once('saveTask-res', (event,res)=>{
            loadingInstance.close();
            if(res.success){
              this.$message.success('任务已保存');
              this.dialogFormVisible = false;
              if(this.taskEdit._id){
                this.updateItemById(this.taskEdit._id);
     
               }else{
                this.taskList.unshift(res.data);
                this.sort();
               
               }
            }
          })
          ipcRenderer.send('saveTask',this.taskEdit);
        } else {
            if (obj["symbol"]) {
              this.currentTab = "0";
            } else if (obj["profitPercent"] || obj["fallBackPercent"]) {
              this.currentTab = "2";
            } else {
              this.currentTab = "1";
            }
            return false;
          }
      });
    },
    onSettingEnter(formName){
    this.$refs[formName].validate((valid, obj) => {
        if (valid) {
          let method = this.moneySettingForm.method;
          let money = this.moneySettingForm.money;
          let count = this.moneySettingForm.count;
          let arr = [];
          if(method == '1'){
              arr = this.fibo(money,count)
          }else if(method == '2'){
              arr = this.square2(money,count)
          }else if(method == '3'){
            arr = this.square3(money,count)
          }

          let buyMoneys = [];
          for(var i in arr){
            buyMoneys[i] = {value:arr[i] + ''};
          }         
          this.taskEdit.buyMoneys = buyMoneys;
          this.showMoneyDialog = false;
        }
      });
    },
    datadragEnd(event) {
      event.preventDefault();
      this.sort();
      
    },
    sort(){
            var list = [];
            for(var i in this.taskList){
              this.taskList[i].sort = i;
              list.push({_id:this.taskList[i]._id,sort:this.taskList[i].sort});
            }
            //更新顺序
            ipcRenderer.send('updateTaskSort',list);
    },
    refresh(){
     this.loadListTask();
    },
    onOpenDisplayer(_id,symbol){
      ipcRenderer.send('openDisplayer',{'id':_id,'symbol':symbol});
    },
    loadSymbol(callback){
      if(this.symbolList.length == 0){
        ipcRenderer.once('listSymbol-res',(event,list)=>{
          console.log('listSymbol-res',list)
          this.symbolList = list;
          callback();
        });
        ipcRenderer.send('listSymbol');
      }else{
        callback();
      }
    },
    async onTestKey(formName){
      this.$refs[formName].validate(async (valid, obj) => {
        if (valid) {
          let loadingInstance = this.$loading({ lock: true,text: 'Loading',spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
             ipcRenderer.once('testKey-res',(event,result)=>{
              console.log('testKey-res',result)
              loadingInstance.close();
                  if(result.success){
                      this.$message.success('连接成功！');
                  }else{
                      this.$message.error(result.data);
                  }
            })
            ipcRenderer.send('testKey',this.keyForm);
        }
      });

     
    },
    onKeySave(){
      ipcRenderer.once('saveKey-res',(event,res)=>{
        console.log('saveKey-res',res)
        if(res.success){
          this.keyFormVisible = false;
          this.$message.success('保存成功。');
          let c = remote.getGlobal("CONFIG");
        }
      })
      ipcRenderer.send('saveKey',this.keyForm);

    },
    onAuthSave(formName){
      this.$refs[formName].validate((valid, obj) => {
        if(valid){
          let formData = {email:this.authForm.email,
                      authCode:this.authForm.authCode};
            ipcRenderer.once('saveAuth-res',(event,res)=>{
              console.log('saveAuth-res',res)
                   ipcRenderer.once('checkAuth-res',(event,result)=>{
                      console.log('checkAuth-res',result)
                      if(result.success){
                        this.authInfo = result.data;
                      }
                    })
                    ipcRenderer.send('checkAuth');
            })
           ipcRenderer.send('saveAuth',formData);
            
        }
      })
    },
    loadKey(){
      ipcRenderer.once('getKey-res',(event,res)=>{
        console.log('getKey-res',res)
        if(res.success && res.data){
          this.keyForm = res.data;
        }
      })
      ipcRenderer.send('getKey');

    },
    loadAuth(){
        ipcRenderer.once('getAuth-res',(event,res)=>{
          console.log('getAuth-res',res)
            if(res.success){
              if(res.data){
                  this.authForm.email = res.data.email;
                  this.authForm.authCode = res.data.authCode;
                }
          }
        })
       ipcRenderer.send('getAuth');
      
       ipcRenderer.once('checkAuth-res',(event,result)=>{
         console.log('checkAuth-res',result)
          if(result.success){
            this.authInfo = result.data;
          }
       })
       ipcRenderer.send('checkAuth')

    },
    onFlicker(){
      ipcRenderer.on('flicker',(event,data) => {
            let el = document.querySelector('#id_' + data.id)
            if(!el){
              return;
            }
            if(this.timerId){
              el.classList.remove('laser-runing');
              clearTimeout(this.timerId)
              this.timerId = null;
            }
            el.classList.add('laser-runing');
            let timerId = setTimeout(function(){
              el.classList.remove('laser-runing');
               this.timerId = null;
            },1000)
            this.timerId = timerId;
      })
    },
     onClose(){
      ipcRenderer.on('close',(event,msg) => {
        ipcRenderer.once('closeTask-res',(event,res)=>{
          console.log('closeTask-res',res)
            this.updateItem(msg.id);
            this.$message('任务已停止');
        })
        ipcRenderer.send('closeTask',{_id:msg.id});
      })
    },
    //关闭任务时会重复执行
    onUpdateItem(){
        ipcRenderer.on('updateItem',(event,msg) => {
          this.updateItem(msg.id);
      })
    },
    updateItemById(id){
      ipcRenderer.once('getTaskById-res',(event,res)=>{
        console.log('getTaskById-res',res)
            if(res.success){
              let doc = res.data;
            for(var i in this.taskList){
              if(this.taskList[i]._id == doc._id){
                this.taskList[i] = doc;
                break;
              }
            }
          }
      })
      ipcRenderer.send('getTaskById',id);

    },
    updateItem(id){
      ipcRenderer.once('getTaskById-res',(event,res)=>{
        console.log('getTaskById-res',res)
        if(res.success){
              let doc = res.data
              for(var i in this.taskList){
                let task = this.taskList[i];
                if(task._id == doc._id){
                  this.taskList[i].state = doc.state + '';
                  this.taskList[i].loopCount = doc.loopCount;
                  break;
                }
              }
            }
      })
      ipcRenderer.send('getTaskById',id);
          
    },
    settingMoney(){
      this.showMoneyDialog = true;
    },
    addMoneyInput(){
      if(this.taskEdit.buyMoneys.length < 10){
          this.taskEdit.buyMoneys.push({value:''})
      }
      
    },
    removeMoneyInput(){
      if(this.taskEdit.buyMoneys.length > 1){
       this.taskEdit.buyMoneys.pop()
      }
    },
    fibo(money,count,scale){
      let arr = [];
      for(let i = 0; i < count; i++){
          let num1,num2,result;
          if(i == 0){
              result = math.bignumber(money);
          }else if(i == 1){
              num1 = num2 = math.bignumber(money)
              result = math.chain(num1).add(num2).done();
          }else{
              num1 = math.bignumber(arr[i-1]);
              num2 = math.bignumber(arr[i-2]);
              result = math.chain(num1).add(num2).done();
          }
          if(scale){  
              arr[i] = math.round(result,scale);
          }else{
              arr[i] = result;
          }
      }
      return arr;
    },
    square2(money,count,scale){
        let arr = [];
        let num = math.bignumber(money);
        let base = math.bignumber(2);
        for (let i = 0; i < count; i++) {
            if(i > 0){
                num = math.chain(num).multiply(base).done();
            }
            arr[i] = num;
        } 
      return arr;
    },
    square3(money,size,scale){
      let arr = [];
      let num = math.bignumber(money);
      let base = math.bignumber(3);
      for (let i = 0; i < size; i++) {
          if(i > 0){
              num = math.chain(num).multiply(base).done();
          }
          arr[i] = num;
      } 
    return arr;
  },
  myRound(num,precision){
    if(precision == undefined || precision <= 0){
        return math.floor(num).toString();
    }else{
        let mulNum = '1'
        for(let i= 0;i < parseInt(precision);i++){
            mulNum += '0';
        }
       
        let tempNum = math.chain(math.bignumber(num)).multiply(math.bignumber(mulNum)).done();
        tempNum =   math.floor(tempNum)
        tempNum = math.chain(math.bignumber(tempNum)).divide(math.bignumber(mulNum)).done();
        return tempNum.toString();
    }

},
  closeWin(){
    ipcRenderer.send('closeWin')
  },
  maxWin(){
     ipcRenderer.send('maxWin')
  },
  minWin(){
    ipcRenderer.send('minWin')
  },
  onSymbolChange(value){
    this.updateTaskCurrency(value);
  },
  updateTaskCurrency(value){
    let currency = null;
    for(let i in this.symbolList){
      if(value == this.symbolList[i].symbol){
        currency = this.symbolList[i];
        break;
      }
    }
    if(currency){
      this.taskQuoteCurrency = currency['quote-currency'];
      this.taskBaseCurrency = currency['base-currency'];
      this.taskAmountPrecision = currency['amount-precision'];
       this.taskValuePrecision = currency['value-precision'];
    }else{
      this.taskQuoteCurrency = '';
      this.taskBaseCurrency = '';
      this.taskAmountPrecision = 8;
      this.taskValuePrecision = 8;
    }
  },
  getAccountBalance(){
    if(this.taskEdit.accountBalance){
      ipcRenderer.send('getCurrencyBalance',{'currency':this.taskBaseCurrency});
      ipcRenderer.on('onCurrencyBalanceRes',(event,res)=>{
        if(res.success){
          this.taskEdit.totalAmount = this.myRound(res.data,this.taskAmountPrecision)
          this.$message.success('加载余额成功：' + this.taskEdit.totalAmount);
        }else{
          this.$message.error('加载余额失败：' + res.data);
        }
      })

    }


  },
  onRadioSymbolChange(value){
     this.updateTaskCurrency(value);
  },
   initSymbol(){
     ipcRenderer.once('initSymbols-res',(event,result)=>{
       console.log('initSymbols-res',result)
     })
      ipcRenderer.send('initSymbols');
  },
  onAccountBalanceChange(checked){
    if(checked){
      if(this.taskEdit.symbol){
          this.updateTaskCurrency(this.taskEdit.symbol);
      }
    }
  },
  loadListTask(){
      let loadingInstance = this.$loading({ lock: true,text: 'Loading',spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'});
      ipcRenderer.once('listTask-res',(event,list)=>{
        console.log('listTask-res',list)
        loadingInstance.close();
         this.taskList = list;
         console.log(this.taskList)
      })
      ipcRenderer.send('listTask');
  }

    
  },
  created(){
    console.log('created');
    this.loadListTask();
  },
  mounted(){
    console.log('mounted')
    ipcRenderer.removeAllListeners('flicker')
    ipcRenderer.removeAllListeners('close')
       ipcRenderer.removeAllListeners('updateItem')
     ipcRenderer.removeAllListeners('windowMax')
      ipcRenderer.removeAllListeners('windowUnmax')
      ipcRenderer.removeAllListeners('checkAuth')

   

    this.onFlicker();
    this.onClose();
    this.onUpdateItem();

    ipcRenderer.on('windowMax',(event,data)=>{
      this.isWindowMaxed = true;
    })
     ipcRenderer.on('windowUnmax',(event,data)=>{
      this.isWindowMaxed = false;
    })

     ipcRenderer.on('checkAuth',(event,data)=>{
        ipcRenderer.once('checkAuth-res',(event,result)=>{
           console.log('checkAuth-res',result)
          if(result.success){
              if(!result.data.valid){
                this.$message.error(result.data.content);
                ipcRenderer.send('closeAllTask');
            }
          }
        })
        ipcRenderer.send('checkAuth')
    })




    
  }
};
</script>

<style lang="less">
#home {
  .place {
    height: 65px;
  }
  .menu {
    position: fixed;
    top: 0px;
    z-index: 99;
    width: 100%;
    -webkit-app-region: drag;
  -webkit-user-select: none;
  .el-menu-item,.el-submenu{
    -webkit-app-region: no-drag;
  }
  
  }
  .logo{
    -webkit-app-region: drag;
    .logo-img{
      display:inline;
      width:130px;
      margin-right:10px;
    }
    .logo-text{
    display:inline;
    }
  }
  .min-max-close-button {
    -webkit-app-region: no-drag;
    position: fixed;
    top: 10px;
    right: 10px; 
    height: 40px;
    z-index: 99999999999;
    display: flex;
    flex-direction: row-reverse;
    .button-group {
      margin: 5px;
    }
  }

  .common-button {
    position: fixed;
    bottom: 10px;
    right: 10px;
    height: 40px;
    z-index: 99;
    display: flex;
    flex-direction: row-reverse;
    .button-group {
      margin: 5px;
    }
  }
  .cell-move {
    transition: transform 1s;
  }
  .new-button{
    position:absolute;
    width:120px;
    height:40px;
    top:50%;
    left:50%;
    margin-left:-60px;
    margin-top:-20px;
  }
  .card-body > div > ul {
    display: flex;
    flex-wrap: wrap;
    .box-card {
      margin: 5px;
      width: 300px;
      position:relative;
      .laser{
        height: 2px;
        position: absolute;
        bottom: 0px;
        left: 0px;
        right: 0px;
        width:0%;
        background-color: #f56058;
        box-shadow: 0px 0px 10px 2px #f56058;
        z-index: 999;
      }
      .laser-runing {
          animation: laser-process 1s linear infinite;
        }
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 30px;
        .left {
          margin-left: 5px;
        }
        .lamp {
          width: 15px;
          height: 15px;
          background-color: #c1c1c1;
          border-radius: 50%;
        }
        .runing {
          animation: bright 1s linear infinite;
        }
      }
      .el-card__header {
        padding: 5px 5px !important;
      }
    }
     .runing-card-border {
          
          animation: card-border 1s linear infinite;
      }
  }

  .el-divider--horizontal {
    margin: 12px 0 !important;
  }

  .el-dialog__body {
      padding-top: 2px;
  }
  div.el-dialog__body div.el-tabs__content{
     position: absolute;
     top:110px;
     bottom: 0;
     left: 30px;
     right: 20px;
     overflow-y: auto;
     background-color: #fff;
     height:280px;
     border-bottom: 2px solid #E4E7ED;
  }

  .el-slider__marks-text {
    width:32px;
    margin-top: 6px;
  }
   
}

  div.el-tabs__content::-webkit-scrollbar{width:10px;height:8px;}
  div.el-tabs__content::-webkit-scrollbar-button{width:10px;height:8px}
  div.el-tabs__content::-webkit-scrollbar-track{background:0 0}
  div.el-tabs__content::-webkit-scrollbar-thumb{background:#383F66;border-radius:5px}
  div.el-tabs__content::-webkit-scrollbar-thumb:hover{background-color:#66B1FF}
  div.el-tabs__content::-webkit-scrollbar-thumb:active{background-color:#17bbaf}

@keyframes laser-process {
   0% {
     width:0%
 }95% {
   width:100%
 }100% {
   width:0%
 }
}


@keyframes bright {
  0% {
    background-color: #13ce66;
    box-shadow: 0px 0px 10px 2px #13ce66;
  }
  50% {
    background-color: #fff;
    box-shadow: none;
  }
  100% {
    background-color: #13ce66;
    box-shadow: 0px 0px 10px 2px #13ce66;
  }
}

.el-dialog__wrapper {
  transition-duration: 0.3s;
}
.dialog-fade-enter-active {
  animation: none !important;
}
.dialog-fade-leave-active {
  transition-duration: 0.15s !important;
  animation: none !important;
}

.dialog-fade-enter-active .el-dialog,
.dialog-fade-leave-active .el-dialog {
  animation-fill-mode: forwards;
}

.dialog-fade-enter-active .el-dialog {
  animation-duration: 0.3s;
  animation-name: anim-open;
  animation-timing-function: cubic-bezier(0.6, 0, 0.4, 1);
}

.dialog-fade-leave-active .el-dialog {
  animation-duration: 0.3s;
  animation-name: anim-close;
}

@keyframes anim-open {
  0% {
    opacity: 0;
    transform: scale3d(0, 0, 1);
  }
  100% {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}

@keyframes anim-close {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: scale3d(0.5, 0.5, 1);
  }
}
</style>
